package com.itheima.service.impl;

import com.itheima.anno.LogOperation;
import com.itheima.exception.DeletionIsNotAllowed;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.Dept;
import com.itheima.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
/**
 * 部门管理业务层实现类
 * */
@Service
public class DeptServiceImpl implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private EmpMapper empMapper;

    /**
     * 查询所有部门
     * */
    @Override
    public List<Dept> list() {
        return deptMapper.selectAll ();
    }

    /**
     * 根据id删除指定部门
     */
    @LogOperation
    @Override
    public void deleteById(Integer id) {
        //根据部门id查询该部门是否还有员工
        Integer count = empMapper.selectByDeptId(id);
        if (count > 0) {
            //该部门有员工，不允许删除
            throw new DeletionIsNotAllowed("该部门有员工，不允许删除");
        }

        //调用map层方法删除指定部门
        deptMapper.deleteById(id);
    }

    /**
     * 添加部门
     */
    @LogOperation
    @Override
    public void add(Dept dept) {
        //基础数据补全
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //调用map层方法添加部门
        deptMapper.add(dept);
    }

    /**
     * 根据id查询部门
     */
    @Override
    public Dept selectById(Integer id) {
        //调用map层方法根据id查询部门并返回
        return deptMapper.selectById(id);
    }

    /**
     * 更新部门
     */
    @LogOperation
    @Override
    public void updateById(Dept dept) {
        //基础数据补全
        dept.setUpdateTime(LocalDateTime.now());

        //调用map层方法更新部门
        deptMapper.updateById(dept);
    }
}
